﻿using H.Config.Configs.Entities;
using H.Configs;
using H.Daos;

namespace H.Config.Configs
{
    /// <summary>
    /// 配置数据基本存储类
    /// </summary>
    public class HConfig : IConfig
    {
        /// <summary>
        /// 类型名称,用于分类存储
        /// </summary>
        protected static string ConfigName;

        /// <summary>
        /// 内部的数据
        /// </summary>
        private readonly IDao Dao;

        ///<inheritdoc/>
        public string this[string key] { get => GetString(key); set => Set(key, value); }

        /// <summary>
        /// 使用一个数据库连接初始化一个配置文件
        /// </summary>
        /// <param name="dao"></param>
        public HConfig(IDao dao, string configName)
        {
            Dao = dao;
            Dao.UpdateTable<CommonConfigEntity>();
            ConfigName = configName ?? string.Empty;
        }

        ///<inheritdoc/>
        public int GetInt(string key, int defaultValue)
        {
            string value = GetString(key);
            return string.IsNullOrEmpty(value) ? defaultValue : int.Parse(value);
        }

        ///<inheritdoc/>
        public string GetString(string key)
        {
            return Dao.Query<CommonConfigEntity>()
                      .Where("type", "=", ConfigName)
                      .Where("key", "=", key)
                      .Value<string>("value");
        }

        ///<inheritdoc/>
        public void Set(string key, string value)
        {
            Dao.Query<CommonConfigEntity>()
               .Where("type", "=", ConfigName)
               .Where("key", "=", key)
               .Update("value", value);
        }

        ///<inheritdoc/>
        public void Set(string key, int value)
        {
            Set(key, value.ToString());
        }
    }
}
